/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.business.service.impl;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.business.domain.Whfa;
import me.zhengjie.business.domain.WhfaFfx;
import me.zhengjie.business.domain.Ymkdz;
import me.zhengjie.business.domain.vo.FwjhVo;
import me.zhengjie.business.domain.vo.KB22;
import me.zhengjie.business.repository.WhfaFfxRepository;
import me.zhengjie.business.repository.YmkdzRepository;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.business.repository.WhfaRepository;
import me.zhengjie.business.service.WhfaService;
import me.zhengjie.business.service.dto.WhfaDto;
import me.zhengjie.business.service.dto.WhfaQueryCriteria;
import me.zhengjie.business.service.mapstruct.WhfaMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://el-admin.vip
* @description 服务实现
* @author xiahongbo
* @date 2022-07-18
**/
@Slf4j
@Service
@RequiredArgsConstructor
public class WhfaServiceImpl implements WhfaService {


    private final YmkdzRepository ymkdzRepository;
    private final WhfaFfxRepository whfaFfxRepository;
    private final WhfaRepository whfaRepository;
    private final WhfaMapper whfaMapper;

    @Override
    public Map<String,Object> queryAll(WhfaQueryCriteria criteria, Pageable pageable){
        Page<Whfa> page = whfaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(whfaMapper::toDto));
    }

    @Override
    public Map<String, Object> queryFwjhVo(WhfaQueryCriteria criteria, Pageable pageable) {
        Page<FwjhVo> page = whfaRepository.queryFwjhVo(criteria.getAkb020(), criteria.getBlurry(), criteria.getDate(), criteria.getSbgs(), pageable);
        return PageUtil.toPage(page);
    }

    @Override
    public List<FwjhVo> queryAllFwjhVo(WhfaQueryCriteria criteria) {
        return whfaRepository.queryAllFwjhVo(criteria.getAkb020(), criteria.getBlurry(), criteria.getDate(), criteria.getSbgs());
    }

    @Override
    public void downloadAllFwjhVo(List<FwjhVo> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (FwjhVo project : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("定点编码", project.getDdbm());
            map.put("居家名称", project.getQymc());
            map.put("姓名", project.getXm());
            map.put("身份证", project.getSfz());
            map.put("方案实施日期", project.getWhrq());
            map.put("计划起始钟点", project.getStime());
            map.put("计划结束钟点", project.getEtime());
            map.put("方案状态", "1".equals(project.getZt()) ? "已生成订单" : "未生成订单");
            map.put("服务类型", "94".equals(project.getFwlx()) ? "生活照护" : "医疗照料");
            map.put("联系电话", project.getLxdh());
            map.put("监护人姓名", project.getJhrxm());
            map.put("监护人电话", project.getJhrdh());
            map.put("护理地址", project.getHldz());
            map.put("护理详址", project.getHldz_xxdz());
            map.put("护理人姓名", project.getHlyxm());
            map.put("护理人电话", project.getHlydh());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    public List<WhfaDto> queryAll(WhfaQueryCriteria criteria){

        String month = criteria.getBisWhfaHwrq();

        month = StringUtils.isEmpty(month) ? DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN).substring(0, 7) : month;

        criteria.setBisWhfaHwrq(month);

        return whfaMapper.toDto(whfaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    public List<WhfaDto> queryMpAll(WhfaQueryCriteria criteria, Pageable pageable) {

        String month = criteria.getBisWhfaHwrq();

        month = StringUtils.isEmpty(month) ? DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN).substring(0, 7) : month;

        criteria.setBisWhfaHwrq(month);

        Page<Whfa> page = whfaRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);

        List<Whfa> list = page.getContent();

        return  whfaMapper.toDto(list);
    }

    @Override
    public List<Whfa> findWhfaByMonth(Long zhid, String month) {

        month = StringUtils.isEmpty(month) ? DateUtil.format(DateUtil.date(), DatePattern.NORM_DATE_PATTERN).substring(0, 6) : month;

        System.out.println(month);

        whfaRepository.findWhfaByMonth(zhid, month);
        return null;
    }

    @Override
    @Transactional
    public WhfaDto findById(String bisWhfaId) {
        Whfa whfa = whfaRepository.findById(bisWhfaId).orElseGet(Whfa::new);
        ValidationUtil.isNull(whfa.getBisWhfaId(),"Whfa","bisWhfaId",bisWhfaId);
        return whfaMapper.toDto(whfa);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public WhfaDto create(Whfa resources) {
        return whfaMapper.toDto(whfaRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<WhfaDto> createZhfa(Whfa resources) {

        String whrqs = resources.getBisWhfaHwrq();
        System.out.println(whrqs);
        List<WhfaDto> list = new ArrayList<>();

        String month = "";
        String[] whrqArray = whrqs.split(",");
        for (int i = 0; i < whrqArray.length; i++) {


            log.info("whrqArray[i]:{}", whrqArray[i]);

            month = whrqArray[i].substring(0, 7);
        }

        List<WhfaFfx> whfaFfxList = resources.getWhfaFfxes();
        // 清空实体中服务项表信息
        resources.setWhfaFfxes(new ArrayList<>());


        Long zhid = resources.getBisWhfaZhsqId();
        String fwlx = resources.getBisWhfaFwlx();

        // 01、94：生活照料；04、95：医疗护理
        fwlx = "01".equals(fwlx) ? "94" : "04".equals(fwlx) ? "95" : "";
        resources.setBisWhfaFwlx(fwlx);
        resources.setBisWhfaZt("0");

        int cnt = whfaRepository.checkFaCnt(zhid, month, fwlx);
        if(fwlx.equals("94")) {
            if(cnt > 8) {
                throw new BadRequestException("生活照料方案计划["+month+"]最多8条计划");
            }
        }
        if(fwlx.equals("95")) {
            if(cnt > 4) {
                throw new BadRequestException("医疗护理方案计划["+month+"]最多4条计划");
            }
        }

        for (int i = 0; i < whrqArray.length; i++) {

            String whrq = whrqArray[i];
            Whfa isExist = whfaRepository.queryByBisWhfaZhsqIdAndBisWhfaHwrq(zhid, whrq);
            if(isExist != null) {
                throw new BadRequestException("方案计划["+whrq+"]已经存在");
            }

            resources.setBisWhfaId(IdUtil.simpleUUID());
            resources.setBisWhfaHwrq(whrq);
            Whfa newWhfa = whfaRepository.save(resources);
            // 保存之前先删除，按方案ID删除
            // whfaFfxRepository.deleteByBisWhfaFaid(newWhfa.getBisWhfaId());
            for (WhfaFfx w : whfaFfxList) {

                w.setBisWhfaFfxSl("1");

                Ymkdz ymkdz = ymkdzRepository.findById(w.getBisWhfaDzid()).orElseGet(Ymkdz::new);
                w.setBisWhfaFfxId(IdUtil.simpleUUID());
                w.setWhfa(newWhfa);
                w.setBisWhfaFaid(newWhfa.getBisWhfaId());
                w.setBisWhfaZhid(newWhfa.getBisWhfaZhsqId());
                w.setBisWhfaFfxFwbm(ymkdz.getBisYmkdzYbbm());
                w.setBisWhfaFfxFwmc(ymkdz.getBisYmkdzMc());
                w.setBisWhfaFfxFwsc(ymkdz.getBisYmkdzFwsc());
                w.setBisWhfaFfxZjm(ymkdz.getBisYmkdzZjm());
                w.setBisWhfaFfxDj(ymkdz.getBisYmkdzDj());
                w.setBisWhfaFfxFwlx(ymkdz.getBisYmkdzFwlx());
                w.setBisWhfaFfxJslx(ymkdz.getBisYmkdzJslx());

                w.setBisWhfaFfxYbmc(ymkdz.getBisYmkdzYbmc());
                w.setBisWhfaFfxYbdj(ymkdz.getBisYmkdzYbdj());
                w.setBisWhfaFfxYbzjm(ymkdz.getBisYmkdzYbzjm());
                w.setBisWhfaFfxFwsc(ymkdz.getBisYmkdzFwsc());

                whfaFfxRepository.save(w);

            }
            WhfaDto whfaDto = whfaMapper.toDto(newWhfa);
            list.add(whfaDto);
        }

        return list;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(Whfa resources) {
        List<WhfaFfx> whfaFfxList = resources.getWhfaFfxes();

        // 清空实体中服务项表信息
        resources.setWhfaFfxes(new ArrayList<>());

        Whfa whfa = whfaRepository.findById(resources.getBisWhfaId()).orElseGet(Whfa::new);
        whfa.copy(resources);


        String fwlx = whfa.getBisWhfaFwlx();

        // 01、94：生活照料；04、95：医疗护理
        fwlx = "01".equals(fwlx) ? "94" : "04".equals(fwlx) ? "95" : "";
        whfa.setBisWhfaFwlx(fwlx);

        whfaRepository.save(whfa);


        // 保存之前先删除，按方案ID删除
        whfaFfxRepository.deleteByBisWhfaFaid(whfa.getBisWhfaId());
        for (WhfaFfx w : whfaFfxList) {

            w.setBisWhfaFfxSl("1");

            Ymkdz ymkdz = ymkdzRepository.findById(w.getBisWhfaDzid()).orElseGet(Ymkdz::new);
            w.setBisWhfaFfxId(IdUtil.simpleUUID());
            w.setWhfa(whfa);
            w.setBisWhfaFaid(whfa.getBisWhfaId());
            w.setBisWhfaZhid(whfa.getBisWhfaZhsqId());
            w.setBisWhfaFfxFwbm(ymkdz.getBisYmkdzYbbm());
            w.setBisWhfaFfxFwmc(ymkdz.getBisYmkdzMc());
            w.setBisWhfaFfxFwsc(ymkdz.getBisYmkdzFwsc());
            w.setBisWhfaFfxZjm(ymkdz.getBisYmkdzZjm());
            w.setBisWhfaFfxDj(ymkdz.getBisYmkdzDj());
            w.setBisWhfaFfxFwlx(ymkdz.getBisYmkdzFwlx());
            w.setBisWhfaFfxJslx(ymkdz.getBisYmkdzJslx());

            w.setBisWhfaFfxYbmc(ymkdz.getBisYmkdzYbmc());
            w.setBisWhfaFfxYbdj(ymkdz.getBisYmkdzYbdj());
            w.setBisWhfaFfxYbzjm(ymkdz.getBisYmkdzYbzjm());
            w.setBisWhfaFfxFwsc(ymkdz.getBisYmkdzFwsc());

            whfaFfxRepository.save(w);

        }
    }

    @Override
    public void deleteAll(String[] ids) {
        for (String bisWhfaId : ids) {
            whfaRepository.deleteById(bisWhfaId);
        }
    }

    @Override
    public void download(List<WhfaDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (WhfaDto whfa : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }
}